371. Sum of Two Integers

1. Question

Given two integers a and b, return the sum of the two integers without using the operators + and -.

2. Examples

Example 1:

Input: a = 1, b = 2
Output: 3

Example 2:

Input: a = 2, b = 3
Output: 5

3. Constraints

  • -1000 <= a, b <= 1000

4. References

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/sum-of-two-integers 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

5. Solutions

这里用到位运算。

and 同1为1

or 同0为0

xor 不同为1

xor相当于不进位的加法

and可以计算出最高位是否需要进位(同1为1,左移1位达到效果)

class Solution {
    public int getSum(int a, int b) {
        return a != 0 ? getSum((a & b) << 1, a ^ b) : b;
    }
}
Copyright © rootwhois.cn 2021-2022 all right reserved,powered by GitbookFile Modify: 2023-03-05 10:55:51

results matching ""

    No results matching ""